<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@taglib prefix="shiro" uri="http://shiro.apache.org/tags" %>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>账单列表</title>
    <link rel="stylesheet" type="text/css" href="/static/plugins/easyui/themes/material/easyui.css">
    <link rel="stylesheet" type="text/css" href="/static/plugins/easyui/themes/icon.css">
    <script type="text/javascript" src="/static/plugins/easyui/jquery.min.js"></script>
    <script type="text/javascript" src="/static/plugins/easyui/jquery.easyui.min.js"></script>
    <script type="text/javascript" src="/static/plugins/easyui/locale/easyui-lang-zh_CN.js"></script>
    <script type="text/javascript">


        // 支付方式(默认没有选择支付方式)
        var payType = "-1";

        var status = "-1";

        $(function () {

            $("#edit_table_body").on("click", "#removeItem", function () {// 删除明细按钮点击事件
                var tr = $(this).closest("tr");
                // 1. 获取所有的tr,判断tr数组是否大于1
                if ($("#edit_table_body tr").size() > 1) {
                    // 2. 如果数量大于1,直接删除当前行
                    tr.remove();
                } else {
                    // 3. 否则清空当前行的数据
                    tr.find("[tag=product]").val("");
                    tr.find("[tag=saleprice]").val("");
                    tr.find("[tag=srotName]").val("");
                    tr.find("[tag=saleCount]").val("");
                    tr.find("[tag=AmountPrice]").html("");
                    tr.find("[tag=remark]").val("");
                    $("#totalAmountBox").html("");
                }
            }).on("blur", "input[tag='saleprice'],input[tag='saleCount']", function () {// 价格和数量框失去焦点时自动计算小计
                var tr = $(this).closest("tr");
                // 获取价格
                var costPrice = tr.find("input[tag='saleprice']").val();
                // 获取数量
                var number = tr.find("input[tag='saleCount']").val();
                // 两个都有值时计算小计并赋值
                if (costPrice && number) {
                    tr.find("span[tag='AmountPrice']").html((costPrice * number).toFixed(2));
                }

                calculateAmountPrice();
            });


            $("#product_dg").datagrid({
                fit:true,
                fitColumns:true,// 列自动收缩
                singleSelect:true,// 单选
                pagination:true,// 分页
                rownumbers:true,// 显示行号
                toolbar:"#product_dg_tb",
                url:"/product/queryForList.do",
                columns:[[
                    {field:'productSn',title:'编号',width:100},
                    {field:'productName',title:'商品',width:100},
                    {field:'integral',title:'积分',width:100},
                    {field:'one',title:'一级分类',width:100,formatter:productSortFormatter},
                    {field:'two',title:'二级分类',width:100,formatter:productSortFormatter},
                    {field:'salePrice',title:'售价',width:100},
                ]],
                onClickRow:function (index, row) {
                    var tr = $("#edit_table_body tr:last");
                    // 2. 清空行中的数据
                    tr.find("[tag='pid']").val(row.id);
                    tr.find("[tag=product]").val(row.productName);
                    tr.find("[tag=saleprice]").val(row.salePrice);
                    tr.find("[tag=srotName]").val(row.two.name);
                    tr.find("[tag=saleCount]").val(1);
                    tr.find("[tag='AmountPrice']").html(row.salePrice.toFixed(2));
                    // 计算总金额
                    calculateAmountPrice();
                },
            });

            // 初始化对话窗口
            $("#pay_dlg").dialog({
                title: '对话窗口',
                width: 380,
                height: 200,
                closed: true,
                cache: false,
                modal: true,
                buttons:'#pay_dlg_bb'
            });




            $("#member_dg").datagrid({
                fit:true,
                fitColumns:true,// 列自动收缩
                singleSelect:true,// 单选
                pagination:true,// 分页
                rownumbers:true,// 显示行号
                toolbar:"#member_dg_tb",
                url:"/memberInfo/query.do",
                columns:[[
                    {field:'name',title:'姓名',width:100},
                    {field:'cardnumber',title:'卡号',width:100},
                    {field:'rankId',title:'等级',width:100},
                    {field:'balance',title:'余额',width:100},
                    {field:'points',title:'积分',width:100},
                    {field:'cutoff',title:'折扣',width:100},
                ]],
                onClickRow:function (index, row) {
                    $("#cardId").val(row.id);
                    $("#cardNumberBox").val(row.cardnumber);
                    $("#saleDiscountBox").val(row.cutoff);
                    $("#saleBalanceBox").val(row.balance);
                },
            });

            $("#orderNumberBox").val((Math.random() * 10000000000 + "").substring(1, 9));
            $("#saleDateBox").val(getNowFormatDate());
        });


        function productSortFormatter(value,row,index) {
            if (value) {
                return value.name;
            }
        }


        function calculateAmountPrice() {
            var total = 0;
            $.each($("span[tag='AmountPrice']"), function (index, ele) {
                total += parseFloat($(ele).html());
            });
            $("#totalAmountBox").html(total.toFixed(2));
        }



        function getNowFormatDate() {
            var date = new Date();
            var seperator1 = "-";
            var seperator2 = ":";
            var month = date.getMonth() + 1;
            var strDate = date.getDate();
            if (month >= 1 && month <= 9) {
                month = "0" + month;
            }
            if (strDate >= 0 && strDate <= 9) {
                strDate = "0" + strDate;
            }
            var currentdate = date.getFullYear() + seperator1 + month + seperator1 + strDate
                + " " + date.getHours() + seperator2 + date.getMinutes()
                + seperator2 + date.getSeconds();
            return currentdate;
        }



        function appendRow() {
            // 1. 获取到表格中的第一行,并克隆
            var tr = $("#edit_table_body tr:first").clone();
            // 2. 清空行中的数据
            tr.find("[tag=product]").val("");
            tr.find("[tag=saleprice]").val("");
            tr.find("[tag=srotName]").val("");
            tr.find("[tag=saleCount]").val("");
            tr.find("[tag=AmountPrice]").html("");
            tr.find("[tag=remark]").val("");
            // 3. 追加到表格中
            tr.appendTo("#edit_table_body");
        }


        // 商品高级查询操作
        function searchProductForm() {
            // 获取关键字
            var keyword = $("input[name='productKeyword']").val();
            // 传人关键字刷新数据表格
            $("#product_dg").datagrid("load",{
                "keyword":keyword
            });
        }

        // 高级查询操作
        function searchMemberForm() {
            // 会员获取关键字
            var keyword = $("input[name='memberKeyword']").val();
            // 传人关键字刷新数据表格
            $("#member_dg").datagrid("load",{
                "keyword":keyword
            });
        }


        function uniqueNumber() {
            var date = Date.now();

            if (date <= uniqueNumber.previous) {
                date = ++uniqueNumber.previous;
                } else {
                uniqueNumber.previous = date;
                }

            return date;
        }


        // 结算
        function clearing() {
            var totalA = parseFloat($("#totalAmountBox").html());
            if (totalA > 0) {
                // 判断是否选择了会员
                var cardNumber = $("#cardNumberBox").val();
                if (cardNumber) {
                    payType = "4";
                    confirmPay();
                } else {
                    // 其他支付方式
                    // 设置对话框标题
                    $("#pay_dlg").dialog("setTitle","结算")
                    // 打开对话框
                    $("#pay_dlg").dialog("open");
                }
            } else {
                $.messager.alert("温馨提示:","请选择要购买的商品!","error");
            }
        }
        // 对话框取消操作
        function cancel() {
            $("#pay_dlg").dialog("close");
        }

        // 确定支付
        function confirmPay() {

            if (payType != "4") {
                payType = getRadioBoxValue("payType")
            }

            $.messager.alert("温馨提示:","是否确定支付?","info",function () {
                status = "2";
                clearingOrPendingOrder();
            });
        }



        function getRadioBoxValue(radioName)
        {
            var obj = document.getElementsByName(radioName);  //这个是以标签的name来取控件
            for(i=0; i<obj.length;i++)    {

                if(obj[i].checked)    {
                    return obj[i].value;
                }
            }
            return "undefined";
        }


        // 挂单
        function pendingOrder() {
            var totalA = parseFloat($("#totalAmountBox").html());
            if (!totalA) {
                $.messager.alert("温馨提示:","请选择要购买的商品!","error");
                return;
            }
            // 判断是否选择了会员
            var cardNumber = $("#cardNumberBox").val();
            if (!cardNumber) {
                $.messager.alert("温馨提示:","请选择会员账号!","error");
                return;
            }

            $.messager.alert("温馨提示:","是否确定挂单?","info",function () {
                status = "1";
                clearingOrPendingOrder();
            });
        }
        
        

        // 结算或者挂单提交数据
        function clearingOrPendingOrder() {
            if (!$("#edit_table_body tr:first [tag='pid']").val()) {
                showDialog("至少选择一条明细!")
                return;
            }

            // 异步提交表单
            $('#order_form').form("submit",{
                url:"/cashier/saveOrUpdate.do",
                onSubmit:function(param){
                    param.status = status;
                    // 重新编排索引
                    $.each($("#edit_table_body tr"), function (index, ele) {
                        param["items["+index+"].product.id"] = $(ele).find("input[tag='pid']").val();
                        param["items["+index+"].salePrice"] = $(ele).find("input[tag='saleprice']").val();
                        param["items["+index+"].number"] = $(ele).find("input[tag='saleCount']").val();
                        param["items["+index+"].remark"] = $(ele).find("input[tag='remark']").val();
                    });
                },
                success:function(data){
                    // 将返回的json字符串转成json对象
                    data = $.parseJSON(data);
                    if (data.success) {
                        $.messager.alert("温馨提示:","操作成功!","info",function () {
                            document.location.reload();//当前页面
                        })
                    } else {
                        $.messager.alert("温馨提示:",data.msg,"error");
                    }
                }
            })
        }
        
        
        
    </script>
</head>
<body>


<div id="cc" class="easyui-layout" data-options="fit:true">
    <div data-options="region:'west',split:false" style="width:40%">
        <form id="order_form">
            <input id="cardId" type="hidden" name="cardId">
            <table>
                <tbody>
                <tr>
                    <td>

                        <span style="font-size: 15%">服务人员: </span>
                        <input id="saleNameBox" name="saleName" value='<shiro:principal property="username"/>'>
                    </td>
                    <td>
                        <span style="font-size: 15%">流水单号: </span>
                        <input id="orderNumberBox" name="orderNumber">
                    </td>
                </tr>
                <tr>
                    <td>
                        <span style="font-size: 15%">业务时间: </span>
                        <input id="saleDateBox" name="saleDate">
                    </td>
                    <td>
                        <span style="font-size: 15%">会员卡号: </span>
                        <input id="cardNumberBox" name="cardNumber">
                    </td>
                </tr>
                <tr>
                    <td>
                        <span style="font-size: 15%">会员折扣: </span>
                        <input id="saleDiscountBox" name="cutoff">
                    </td>
                    <td>
                        <span style="font-size: 15%">会员余额: </span>
                        <input id="saleBalanceBox" name="balance">
                    </td>
                </tr>
                <tr>
                    <td>
                        <span style="font-size: 15%">金额小计: </span>
                        <span id="totalAmountBox" name="totalAmount" style="font-size: 15%"></span>
                    </td>
                    <td>
                    </td>
                </tr>
                <tr></tr>
                <tr align="center">
                    <td>
                        <a class="easyui-linkbutton" onclick="pendingOrder()"
                           data-options="iconCls:'icon-save', width:100, height:30, text:'挂单'"></a>
                    </td>
                    <td>
                        <a class="easyui-linkbutton" onclick="clearing()"
                           data-options="iconCls:'icon-sum', width:100, height:30, text:'结算'"></a>
                    </td>
                </tr>
                </tbody>
            </table>
            <br/>
            <a class="easyui-linkbutton" onclick="appendRow()" data-options="width:100, height:20, text:'添加明细'"></a>
        </form>
        <table id="myTable" class="myOrder" cellspacing="0" cellpadding="0" border="0" style="width: auto">
            <thead align="center">
                <tr>
                    <th width="10" style="font-size: 15%"></th>
                    <th width="80" style="font-size: 15%">货品</th>
                    <th width="80" style="font-size: 15%">品牌</th>
                    <th width="80" style="font-size: 15%">价格</th>
                    <th width="80" style="font-size: 15%">数量</th>
                    <th width="80" style="font-size: 15%">金额</th>
                    <th width="80" style="font-size: 15%">备注</th>
                    <th width="80" style="font-size: 15%"></th>
                </tr>
            </thead>
            <tbody id="edit_table_body">
            <tr align="center">
                <td></td>
                <td>
                    <input id="product_name" tag="product" style="width:50px"/>
                    <input type="hidden" tag="pid"/>
                </td>
                <td>
                    <input id="productSrotName" tag="srotName"  style="width:50px"/>
                </td>
                <td>
                    <input id="salePrice" tag="saleprice"  style="width:50px"/>
                </td>

                <td>
                    <input id="saleCount" tag="saleCount"  style="width:50px"/>
                </td>

                <td>
                    <span tag="AmountPrice" style="font-size: 15%"></span>
                </td>
                <td>
                    <input id="remark" tag="remark"  style="width:50px"/>
                </td>
                <td>
                    <input type="button" id="removeItem" value="删除明细" style="width:60px"/>
                </td>
            </tr>
            </tbody>
            <tfoot>
                <tr align="center" style="height: 50px">
                    <td colspan="8">
                        <a class="easyui-linkbutton" onclick="pendingOrder()" data-options="width:100, height:20, text:'确定保存'"></a>
                    </td>
                </tr>
            </tfoot>
        </table>
    </div>





    <div data-options="region:'center'">
        <div class="easyui-tabs" data-options="fit:true">
            <div title="商品列表" style="display:none;">
                <table id="product_dg"></table>
            </div>
            <div title="会员列表" style="display:none;">
                <table id="member_dg"></table>
            </div>
        </div>
    </div>
    <div id="product_dg_tb">
        <td><input name="productKeyword" class="easyui-textbox" style="width: 200px" prompt="请输入商品编号或名称"></td>
        <a class="easyui-linkbutton" onclick="searchProductForm();" data-options="iconCls:'icon-search',text:'搜索',plain:true"></a>
    </div>
    <div id="member_dg_tb">
        <td><input name="memberKeyword" class="easyui-textbox" style="width: 200px" prompt="请输入姓名/电话/卡号"></td>
        <a class="easyui-linkbutton" onclick="searchMemberForm();" data-options="iconCls:'icon-search',text:'搜索',plain:true"></a>
    </div>


</div>



<div id="pay_dlg">
    <div style="height: 22%;margin-left: 15%">
        支付类型:
        <input type="radio" checked="checked" name="payType" value="0">现金
        <input type="radio" name="payType" value="1">储蓄卡
        <input type="radio" name="payType" value="2">支付宝
        <input type="radio" name="payType" value="3">微信
    </div>
</div>
<div id="pay_dlg_bb">
    <a class="easyui-linkbutton" onclick="confirmPay()" data-options="iconCls:'icon-ok',text:'确定',plain:true"></a>
    <a class="easyui-linkbutton" onclick="cancel()" data-options="iconCls:'icon-cancel',text:'取消',plain:true"></a>
</div>
</body>
</html>
